package com.tools.handler.analysis;

import com.tools.common.result.Result;
import com.tools.handler.StepHandler;
import com.tools.pojo.data.MedicalAnalysisRequestDTO;
import com.tools.pojo.workflow.bo.StepContext;
import com.tools.utils.DTOConverter;
import com.tools.utils.ValidationResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@Slf4j
@Component
@RequiredArgsConstructor
public class MedicalDataReceiveStepHandler implements StepHandler {


    private static final String STEP_CODE = "DATA_RECEIVE";
    private final DTOConverter dtoConverter;

    @Override
    public String getStepCode() {
        return STEP_CODE;
    }

    @Override
    public Result<?> execute(StepContext context) {
        try {
            log.info("开始执行医疗数据接收步骤，流程实例ID: {}", context.getFlowInstanceId());

            // 从上下文中获取原始JSON数据
            Map<String, Object> contextData = context.getContextData();
            LinkedHashMap<String,Object> jsonData = (LinkedHashMap<String,Object>) contextData.get("rawJsonData");
            if (jsonData == null || jsonData.isEmpty()) {
                return Result.fail("未找到JSON数据");
            }

            // 将JSON转换为DTO对象
            MedicalAnalysisRequestDTO requestDTO;
            requestDTO = dtoConverter.convertToMedicalAnalysisRequest(jsonData);

            // 验证DTO对象
            ValidationResult validation = dtoConverter.validateMedicalAnalysisRequest(requestDTO);
            if (!validation.isValid()) {
                return Result.fail("数据验证失败: " + validation.getMessage());
            }

            // 提取规则ID
            var ruleIds = requestDTO.getRuleIds();

            // 将解析后的DTO和相关信息存入上下文
            context.putContextData("medicalRequestDTO", requestDTO);
            context.putContextData("parsedData", dtoConverter.convertToMap(requestDTO));
            context.putContextData("dataType", "MEDICAL_RECORD_DTO");
            context.putContextData("ruleIds", ruleIds);
            context.putContextData("sysCode", requestDTO.getSysCode());
            context.putContextData("taskId", requestDTO.getTaskId());
            context.putContextData("totalPatients", requestDTO.getPatientDtos().size());

            // 记录患者统计信息
            Map<String, Object> patientStats = calculatePatientStatistics(requestDTO);
            context.putContextData("patientStatistics", patientStats);

            log.info("医疗数据接收步骤执行成功，系统代码: {}, 患者数: {}, 规则数: {}",
                    requestDTO.getSysCode(), requestDTO.getPatientDtos().size(), ruleIds.size());

            return Result.success("医疗JSON数据接收并转换为DTO成功", patientStats);

        } catch (Exception e) {
            log.error("医疗数据接收步骤执行失败", e);
            return Result.fail("医疗数据接收失败: " + e.getMessage());
        }
    }

    /**
     * 计算患者统计信息
     */
    private Map<String, Object> calculatePatientStatistics(MedicalAnalysisRequestDTO requestDTO) {
        Map<String, Object> stats = new HashMap<>();
        stats.put("totalPatients", requestDTO.getPatientDtos().size());

        // 性别统计
        long maleCount = requestDTO.getPatientDtos().stream()
                .filter(patient -> "1".equals(patient.getGend()))
                .count();
        long femaleCount = requestDTO.getPatientDtos().stream()
                .filter(patient -> "2".equals(patient.getGend()))
                .count();

        stats.put("maleCount", maleCount);
        stats.put("femaleCount", femaleCount);

        // 诊断统计
        Map<String, Long> diagnosisStats = new HashMap<>();
        for (var patient : requestDTO.getPatientDtos()) {
            String mainDiagnosis = patient.getMainDiagnosis();
            if (mainDiagnosis != null) {
                diagnosisStats.merge(mainDiagnosis, 1L, Long::sum);
            }
        }
        stats.put("diagnosisStats", diagnosisStats);

        return stats;
    }

}
